package com.ce.pub.process.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.query.Query;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.io.FilenameUtils;


import com.ce.framework.constants.WebConstants;
import com.ce.framework.datamaintain.action.DataMaintainAction;
import com.ce.framework.exception.AppException;
import com.ce.pub.process.view.ProcessDefinitionView;

public class ProcessDefinitionAction extends DataMaintainAction {

	private static final long serialVersionUID = 1L;

	private RepositoryService repositoryService;

	private File process;

	private String processFileName;

	/**
	 * 查询条件
	 */
	protected String definitionKey;
	private String definitionName;

	public void setRepositoryService(RepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}

	@Override
	protected String searchDataJs() throws AppException {
		List<ProcessDefinitionView> result = new ArrayList<ProcessDefinitionView>();
		ProcessDefinitionQuery processDefinitionQuery = repositoryService
				.createProcessDefinitionQuery().orderByDeploymentId().desc();
		int rowCount = Integer.parseInt(Long.toString(processDefinitionQuery
				.count()));
		List<ProcessDefinition> processDefinitionList = processDefinitionQuery
				.list();
		// listPage(0, 100);
		ProcessDefinitionView view = null;
		// 二次封装解决输出json异常
		for (ProcessDefinition processDefinition : processDefinitionList) {
			String deploymentId = processDefinition.getDeploymentId();
			Deployment deployment = repositoryService.createDeploymentQuery()
					.deploymentId(deploymentId).singleResult();
			view = new ProcessDefinitionView();
			view.setVcId(processDefinition.getDeploymentId());
			view.setKey(processDefinition.getKey());
			view.setName(processDefinition.getName());
			view.setVersion(processDefinition.getVersion());
			view.setDeploymentTime(deployment.getDeploymentTime());
			result.add(view);
		}
		this.rows = result;
		this.total = rowCount;
		return JSON;
	}

	/*
	 * 产生query 处理条件
	 */
	public Query createQuery() {
		ProcessDefinitionQuery query = repositoryService
				.createProcessDefinitionQuery();
		// 查询条件
		if (null != definitionName && !"".equals(definitionName.trim())) {
			query.processDefinitionNameLike(definitionName);
		}
		if (null != definitionKey && !"".equals(definitionKey.trim())) {
			query.processDefinitionKey(definitionKey);
		}
		return query;
	}

	public String toDeploy() {
		return "openAddPage";
	}

	public String deploy() {
		try {
			InputStream fileInputStream = new FileInputStream(process);
			String extension = FilenameUtils.getExtension(processFileName);
			// zip里包含流程文件(xml、bpmn)及表单文件(jsp)
			if (extension.equals("zip")) {
				ZipInputStream in = new ZipInputStream(fileInputStream);
				ZipEntry entry = null;
				while ((entry = in.getNextEntry()) != null) {
					if (!entry.isDirectory()) {
						extension = FilenameUtils.getExtension(entry.getName())
								.toLowerCase();
						if ("xml".equals(extension) || "bpmn".equals(extension)) {
							repositoryService.createDeployment()
									.addInputStream(entry.getName(), in)
									.deploy();
						}
						if ("jsp".equals(extension)) {
							String path = this.getRequest().getSession()
									.getServletContext().getRealPath("/")
									+ "process/";
							path = path
									+ FilenameUtils
											.getBaseName(processFileName) + "/";
							File file = new File(path);
							if (!file.exists()) {
								file.mkdirs();
							}
							FileOutputStream out = new FileOutputStream(path
									+ entry.getName());
							int temp = -1;
							while ((temp = in.read()) != -1) {
								out.write(temp);
							}
							out.flush();
							out.close();
						}
					}
					in.closeEntry();
				}
				in.close();
			} else if (extension.equals("bar")) {
				ZipInputStream zip = new ZipInputStream(fileInputStream);
				repositoryService.createDeployment().addZipInputStream(zip)
						.deploy();
			} else {// 单独的流程文件
				repositoryService.createDeployment()
						.addInputStream(processFileName, fileInputStream)
						.deploy();
			}
			fileInputStream.close();

		} catch (Exception e) {
			return this.returnInfoForJS(false, e.getMessage());
		}
		return this.returnInfoForJS(true, null);
	}

	public String delete() {
		String[] delIds = this
				.getParameterValues(WebConstants.SELECT_ITEMS_NAMES);
		repositoryService.deleteDeployment("1", true);
		for (String id : delIds) {
			repositoryService.deleteDeployment("1", true);
		}
		return this.returnInfoForJS(true, null);
	}

	public String getDefinitionName() {
		return definitionName;
	}

	public void setDefinitionName(String definitionName) {
		this.definitionName = definitionName;
	}

	public void setProcess(File process) {
		this.process = process;
	}

	public void setProcessFileName(String processFileName) {
		this.processFileName = processFileName;
	}

	public String getDefinitionKey() {
		return definitionKey;
	}

	public void setDefinitionKey(String definitionKey) {
		this.definitionKey = definitionKey;
	}

}
